package com.ggb.smartstudy.utils;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author gefangjie
 */
// 自定义密码加密器
@Component
public class ShaPasswordEncoder implements PasswordEncoder {

    // 使用SHA-256算法对密码进行加密
    @Override
    public String encode(CharSequence rawPassword) {
        try {
            // 获取SHA-256算法实例
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            // 对密码进行加密
            byte[] hashedBytes = md.digest(rawPassword.toString().getBytes());
            // 将加密后的密码转换为Base64字符串
            return Base64.getEncoder().encodeToString(hashedBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    // 判断密码是否匹配
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return encode(rawPassword).equals(encodedPassword);
    }
}
